package com.lansi.controller;

import java.io.File;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.lansi.bean.ResponseResult;
import com.lansi.bean.User;
import com.lansi.company.bean.Company;
import com.lansi.company.service.ICompanyService;
import com.lansi.service.IKeyService;
import com.lansi.service.IUserService;



@Controller
public class UserController extends BaseController{
	//依赖注入
	@Resource
	private IUserService userService;
	@Resource
	private IKeyService keyService;
	@Resource
	private ICompanyService companyService;
	
	

	//测试
	@RequestMapping("/index2.do")
	public String showRegisters() {
		return "index3";
	}
	
	//验证用户名是否存在
	@RequestMapping("/checkUsername.do")
	@ResponseBody
	public ResponseResult<Void> checkUsername( @RequestBody Map<String,String> map){
		String username=map.get("username");		
		System.out.println(username);
		
		//1.创建rr对象
		ResponseResult<Void> rr = new ResponseResult<Void>();
		//2.调用业务层checkUsername(username);返回boolean b
		boolean b =userService.checkUsername(username);
		if(b) {
			//3.b==true; state=0; message="用户名不可以使用"
			rr.setState(-1);
			rr.setMessage("用户名不可以使用");
		}else {
			//4.b=false; state=1; message="用户名可以使用"
			rr.setState(1);
			rr.setMessage("用户名可以使用");
		}
			//5.return rr;
			return rr;
	}
	
	//验证邮箱是否存在
		@RequestMapping("/checkEmail.do")
		@ResponseBody
		public ResponseResult<Void> checkEmail( @RequestBody Map<String,String> map){
			String email=map.get("email");
			System.out.println(email);
			
			//1.创建rr对象
			ResponseResult<Void> rr = new ResponseResult<Void>();
			//2.调用业务层checkEmail(emil);返回boolean b
			boolean b =userService.checkEmail(email);
			if(b) {
				//3.b==true; state=0; message="邮箱不可以使用"
				rr.setState(-1);
				rr.setMessage("邮箱不可以使用");
			}else {
				//4.b=false; state=1; message="邮箱可以使用"
				rr.setState(1);
				rr.setMessage("邮箱可以使用");
			}
				return rr;
		
		}
		//验证手机是否存在
		@RequestMapping("/checkPhone.do")
		@ResponseBody
		public ResponseResult<Void> checkPhone( @RequestBody Map<String,String> map){			
			String phone=map.get("phone");
			System.out.println(phone);
			
			ResponseResult<Void> rr = new ResponseResult<Void>();
			boolean b = userService.checkPhone(phone);
			if(b) {
				rr.setState(0);
				rr.setMessage("电话号码不可以使用");
			}else {
				rr.setState(1);
				rr.setMessage("电话号码可以使用");
			}
				return rr;
		}
		
		//处理用户注册
		@RequestMapping("/register.do")
		@ResponseBody
		public Map<String, Object> register( @RequestBody Map<String,String> map){
			 String username=map.get("username");
			 String key=map.get("key");
			 String tel=map.get("tel");
			 String mail=map.get("email");
			 String regcode=map.get("regcode");
			 
			 System.out.println("用户注册:register.do");
			 System.out.println("用户名:"+username+"密码:"+key+"手机:"+tel+"邮箱:"+mail+"注册码:"+regcode);
			 
				Map<String,Object> model = new HashMap<String,Object>();
				boolean r = keyService.checkRegcode(regcode);//true 数据库存在此用户信息
				boolean m =keyService.checkEmail(mail);
				boolean umail= userService.checkEmail(mail);
				boolean yuser =userService.checkUsername(username);
				boolean ytel =userService.checkPhone(tel);
				boolean tellength = tel.matches("^1[0-9]{10}$");
				/*System.out.println(r);
				System.out.println(m);
				System.out.println(!umail);
				System.out.println(username);
				System.out.println(key);
				System.out.println(tel);				
				System.out.println(mail);
				System.out.println(regcode);*/
				if(r && m && !umail &&  !yuser && !ytel && tellength ) {
					try {
						System.out.println("正在注册");
						String sn=regcode.substring(0, 4);//截取注册码前4位
						User user = new User();
						user.setUsername(username);
						user.setSn(sn);
						user.setUserkey(key);
						user.setTel(tel);
						user.setUsermail(mail);
						user.setCtime(new Date());
						user.setPrio("1");			
						
						userService.register(user);						
						model.put("code", "1");
						
					} catch (RuntimeException e) {
						model.put("code", "-1");
						model.put("desc", "此用户已存在/此手机号已存在/其它错误");
					}
				}else {
					model.put("code", "-1");
					model.put("desc", "此用户已存在/此手机号已存在/其它错误");
				}
					
				return model;
				}
		
		//修改用户信息
		@RequestMapping("/updateUser.do")
		@ResponseBody
		public ResponseResult<Void> updateUser(
							 HttpSession session,
							  @RequestBody Map<String,String> map){
			 String id= map.get("id");
			 String username= map.get("username");
			 String sn= map.get("sn");
			// String userkey=(String) map.get("userkey");
			 String tel=map.get("tel");
			 String usermail= map.get("usermail");										
			 String prio= map.get("prio");
			 
			 System.out.println("修改个人信息:updateUser.do");
			 System.out.println("id"+id+"用户名:"+username+"公司编号:"+sn+"手机:"+tel+"邮箱:"+usermail+"权限:"+prio);
			//1.创建rr对象
			 ResponseResult<Void> rr = new  ResponseResult<Void>();
					
				 try {	
					 
					 Date date =new Date(); 
					 userService.updateUser(Integer.valueOf(id), username, sn,  tel,usermail,date,prio);
					 //来获取user对象
					// User user = userService.getUserById(this.getId(session));
					 //覆盖session的user对象
					//session.setAttribute("user",user);
					 
					rr.setState(1);
					rr.setMessage("修改成功");
				} catch (RuntimeException e) {
					rr.setState(0);
					rr.setMessage(e.getMessage());
				}
			
				return rr;
					
				}
		
		//处理批量删除用户
		@RequestMapping("/delUser.do")
		@ResponseBody
		public ResponseResult<Void> delUser( @RequestBody Map<String,Integer[]> map) {
			Integer[] ids= map.get("ids");
			System.out.println("删除人员个数:"+ids.length);
			ResponseResult<Void> rr = new ResponseResult<Void>();
			
			userService.delUser(ids);
			rr.setState(1);
			rr.setMessage("删除成功");
			return rr;
		}
		
		//单个删除
		@RequestMapping("/delById.do")
		@ResponseBody
		public ResponseResult<Void>  delById(  @RequestBody Map<String,Integer> map) {
			Integer id =map.get("id");
			System.out.println("删除注册码id:"+id);
			ResponseResult<Void> rr = new ResponseResult<Void>();
			
			userService.delById(id);
			rr.setState(1);
			rr.setMessage("删除成功");
			return rr;
		}
		
		//查询出所有的用户信息
		@RequestMapping("/getUser.do")
		@ResponseBody
		public ResponseResult<List<User>> getUser( @RequestBody Map<String,Integer> map){
			Integer page=map.get("page");
			System.out.println("用户查询页数:"+page);
			
			ResponseResult<List<User>> rr = new ResponseResult<List<User>>();
			Integer Usercount =userService.getUsercount();//数据库用户数量
			if(page==null) {
				page=1;
			}
			System.out.println(page);
			Integer offset = (page-1)*10;//跳过的页数
			System.out.println(offset);
			List<User> list = userService.getUser(offset, 10);//offset跳过的条数, count每页显示的页数
			rr.setData(list);
			rr.setState(1);
			rr.setMessage(Usercount.toString());//
			return rr;
		}
		//用户名查询--手机--邮箱--都可以查询
		@RequestMapping("/getPerson.do")
		@ResponseBody
		public ResponseResult<User> getPerson(  @RequestBody Map<String,String> map){
			String useraccount=map.get("useraccount");	
			System.out.println("用户名-手机-邮箱:"+useraccount);
			ResponseResult<User> rr = new ResponseResult<User>();
			User list=null;
			//手机
			if(useraccount!=null  && useraccount.matches("^1[0-9]{10}$")) {
				 list = userService.getTel(useraccount);
			}
			//用户名
			else if(useraccount!=null && useraccount.matches("[A-Z,a-z,0-9]*")) {
				 list = userService.getUsername(useraccount);
			}
			//邮箱
			else if(useraccount!=null && useraccount.contains("@") && useraccount.contains(".")) {
				 list = userService.getUsermail(useraccount);
			}
			
			rr.setData(list);
			rr.setState(1);
			rr.setMessage("1");//页数
			return rr;
		}		
		//用户名查询
		@RequestMapping("/getUsername.do")
		@ResponseBody
		public ResponseResult<User> getUsername( @RequestBody Map<String,String> map){
			String username=map.get("username");
			
			ResponseResult<User> rr = new ResponseResult<User>();
			User list = userService.getUsername(username);
			rr.setData(list);
			rr.setState(1);
			rr.setMessage("1");//页数
			return rr;
		}		
		//手机查询
		@RequestMapping("/getTel.do")
		@ResponseBody
		public ResponseResult<User> getTel( @RequestBody Map<String,String> map){
			String tel = map.get("tel");
			
			ResponseResult<User> rr = new ResponseResult<User>();
			User list = userService.getTel(tel);
			rr.setData(list);
			rr.setState(1);
			rr.setMessage("1");//页数
			return rr;
		}
		//邮箱查询
		@RequestMapping("/getUsermail.do")
		@ResponseBody
		public ResponseResult<User> getUsermail( @RequestBody Map<String,String> map){
			String usermail = map.get("usermail");
			
			ResponseResult<User> rr = new ResponseResult<User>();
			User list = userService.getUsermail(usermail);
			rr.setData(list);
			rr.setState(1);
			rr.setMessage("1");//页数
			return rr;
		}
				
		//登录功能
		//@SuppressWarnings("unused")
		@RequestMapping("/LoginValidator.do")
		@ResponseBody
		public Map<String, Object> login(
					 HttpSession session,				 
					 @RequestBody Map<String,String> map){
			
			Map<String,Object> model = new HashMap<String,Object>();
			String loginaccount=map.get("loginaccount");
			String key=map.get("key");
			System.out.println(loginaccount);
			try {
				User user = userService.login(loginaccount, key, null);
				String sn1 = user.getSn();
				//Company company =iCompanyService.getSn(sn1);
				Company company= companyService.getSn(sn1);
				System.out.println(user);
				session.setAttribute("user", user);
				model.put("username",user.getUsername());
				model.put("code", "1");
				model.put("tel", user.getTel());
				model.put("mail", user.getUsermail());
				model.put("companyid", company.getSn());
				model.put("companystr", company.getAddr());
				model.put("priority", user.getPrio());
				
			} catch (Exception e) {
				model.put("code", "-1");
				model.put("desc", "用户名或密码错误");
			}
			return model;						
			
		}
		
		//退出
		@RequestMapping("/exit.do")
		@ResponseBody
		public  ResponseResult<Void> exit(HttpSession session) {
			ResponseResult<Void> rr = new ResponseResult<Void>();
			//session失效
			session.invalidate();
			rr.setState(1);
			rr.setMessage("退出成功");
			return rr;
			
		}
		
		//修改密码和用户信息
		@RequestMapping("/updatePerson.do")
		@ResponseBody
		public ResponseResult<Void> updatePerson( @RequestBody Map<String,String> map,
				HttpSession session/*,Integer id, String oldPwd, String newPwd,
				String username,String sn,String tel,String usermail,String prio*/
				){
			 String id= map.get("id");
			 String username= map.get("username");
			 String sn= map.get("sn");
			 String oldPwd=(String) map.get("oldPwd");
			 String newPwd=(String) map.get("newPwd");
			 String tel=map.get("tel");
			 String usermail= map.get("usermail");										
			 String prio= map.get("prio");
			ResponseResult<Void> rr = new ResponseResult<Void>();
			try {
				Date time =new Date();
				if(newPwd!=null) {
					userService.changePassword(Integer.valueOf(id), oldPwd, newPwd);
				}	
				if(username!=null && sn!=null && tel!=null && usermail!=null && prio!=null ) {
					boolean yuser =userService.checkUsername(username);
					boolean ytel =userService.checkPhone(tel);
					boolean yemail= userService.checkEmail(usermail);
					 if( !yuser && !ytel && !yemail) {
						 userService.updateUser(Integer.valueOf(id), username, sn, tel, usermail, time, prio);
						 rr.setState(1);
						 rr.setMessage("修改成功");
					 }else {
						 
					 }
										
				}
				rr.setState(1);
				rr.setMessage("修改成功");
				
			} catch (RuntimeException e) {
				rr.setState(0);
				rr.setMessage(e.getMessage());
			}
			return rr;
		}
		
		//上传图片
		@RequestMapping("/upload.do")
		@ResponseBody
		public ResponseResult<Void> upload(
					@RequestParam("file") MultipartFile file,
					HttpSession session) throws Exception{
			ResponseResult<Void> rr = new ResponseResult<Void>();
			//获取服务器的真实路径
			String path = session.getServletContext().getRealPath("/");
			System.out.println(path);
			//上传
			file.transferTo(new File(path,"/upload/"+file.getOriginalFilename()));
			//保存头像
			userService.updateImage("/upload/"+file.getOriginalFilename(),this.getId(session));
			//更新session中的user对象
			session.setAttribute("user",userService.getUserById(this.getId(session)));
			rr.setState(1);
			rr.setMessage("上传图片成功");
			return rr;
		}
		//测试
		 @RequestMapping("/test.do")
		 @ResponseBody
		    public Map<String, Object>  test(Integer id ,String name) {
			Map<String,Object> model = new HashMap<String,Object>();
			 model.put("1", id);
			 model.put("1", name);
		       return model;
		    }
}
